package com.sw.rpc.consumer;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Callable;

/**
 * @author sw
 * @project zdy-rpc
 * @description
 * @date 2020/5/17 21:10
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    //通道上下文
    private ChannelHandlerContext context;
    //返回结果
    private String result;

    private Object para;
    private Channel channel;

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 发送数据 进入线程等待
     * @return
     * @throws InterruptedException
     */
    public synchronized Object call() throws InterruptedException {
        if (channel == null) {
            return null;
        }
        System.out.println("发送消息到服务端" + channel.remoteAddress());

        channel.writeAndFlush(para);
        System.out.println("怎么了？");
        Instant startInstant = Instant.now();
        // 超时时间10s
        long waitTime = 10000;
        wait(waitTime);
        Instant endInstance = Instant.now();
        // 如果超时了，就返回一个timeout
        if (Duration.between(startInstant, endInstance).getSeconds() >= waitTime / 1000) {
            System.out.println("返回超时");
            return "timeout";
        }
        return result;
    }

    /**
     * 处理结果，唤起发送等代线程
     * @param ctx
     * @param msg
     */
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        result = msg.toString();
        notify();
    }

    public Object getPara() {
        return para;
    }

    public void setPara(Object para) {
        this.para = para;
    }
}
